package com.yushu.common.aspect;

import com.alibaba.fastjson.JSON;
import com.yushu.authority.pojo.vo.PmUserVO;
import com.yushu.base.pojo.bo.Log;
import com.yushu.base.service.LogService;
import com.yushu.common.anno.LogAop;
import com.yushu.common.shiro.ShiroUtil;
import com.yushu.common.util.string.UUIDUtils;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.Date;
import java.util.Map;



 /** 系统日志，切面处理类
 * @author test
 * @CreateDate 2020-12-03 15:47:25
 */
@Aspect
@Component
public class LogAdvice {
    private Logger logger = Logger.getLogger(LogAdvice.class);


    @Autowired
    private LogService logService;

    @Pointcut("@annotation(com.yushu.common.anno.LogAop)")
    public void logPointCut() {
    }

    public long times;

    @Around("logPointCut()")
    public Object around(ProceedingJoinPoint point) throws Throwable {
        Object result = null;

        long beginTime = System.currentTimeMillis();
        //执行方法
        result = point.proceed();
        //执行时长(毫秒)
        times = System.currentTimeMillis() - beginTime;
        return result;
    }

    /**
     * 当方法正常返回是执行
     *
     * @param point
     */
    @AfterReturning("logPointCut()")
    public void doAfter(JoinPoint point) {

        try {

            // 获取方法名称
            MethodSignature methodName = (MethodSignature) point.getSignature();
            Method method = methodName.getMethod();
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            LogAop logAop = method.getAnnotation(LogAop.class);
            String ip = (String) ShiroUtil.getSessionAttribute("ip");

            Log sysLog = new Log();

            if (logAop != null) {
                sysLog.setTitle(logAop.value());
            }
            sysLog.setCreateTime(new Date());
            sysLog.setId(UUIDUtils.getUUID32());
//            sysLog.setUserName((sysUser != null) ? sysUser.getUserName() : "system");
            sysLog.setUrl(request.getRequestURI());
            Map map = request.getParameterMap();
            Class[] paramTypes = method.getParameterTypes();

            sysLog.setParams(JSON.toJSONString(map));
            String classType = point.getTarget().getClass().getName();
            Class<?> clazz = Class.forName(classType);
            String clazzName = clazz.getName();

            //获得方法的参数
            Object[] args = point.getArgs();

            String methodName2 = point.getSignature().getName(); // 获取方法名称

            // 获取参数名称和值
//            StringBuffer sb = LogAopUtil.getNameAndArgs(this.getClass(), clazzName, methodName2, args);
//            sysLog.setParams(sb.toString());
            sysLog.setParams("");
            if (StringUtils.isNotEmpty(ip) && ip.startsWith("{")) {

                JSONObject json = JSONObject.fromObject(ip);
                String country = JSONObject.fromObject(json.get("data")).get("country").toString();
                String region = JSONObject.fromObject(json.get("data")).get("region").toString();
                String city = JSONObject.fromObject(json.get("data")).get("city").toString();
                String county = JSONObject.fromObject(json.get("data")).get("county").toString();
                String isp = JSONObject.fromObject(json.get("data")).get("isp").toString();
                String area = JSONObject.fromObject(json.get("data")).get("area").toString();
                String address2 = country + "/";
                address2 += region + "/";
                address2 += city + "/";
                address2 += county;
                sysLog.setLgCountry(country);
                sysLog.setLgArea(area);
                sysLog.setLgRegion(region);
                sysLog.setLgCity(city);
                sysLog.setLgCounty(county);
                sysLog.setLgIsp(isp);
                sysLog.setLgAddress(address2);

            }

            //保存日志
            sysLog.setExecutionTime((int) times);

            //TODO 2019年7月29日00:47:52 需要修复
            logService.insert(sysLog);
        } catch (Exception e) {
            logger.error(e.getMessage());
        }


    }
}
